﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace ContractDemo
{
    static class SecretHelper
    {
        public static readonly string appCode = "E7067452087193305868";
        public static readonly string appSecret = "922w327kb$s4K&$hpv%Nff3WtZ811&5G5d512t6XhGS6UzSG03&6$3yQj0^#9&0M";

        private static readonly DateTime TimeStampStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        /// <summary>
        /// 添加鉴权参数
        /// </summary>
        /// <param name="paramDict">业务参数</param>
        /// <param name="path">请求路径</param>
        public static void AddAuthParam(Dictionary<string, string> paramDict, string path)
        {
            TimeSpan ts = DateTime.UtcNow - TimeStampStartTime;
            paramDict["version"] = "v1";
            paramDict["appCode"] = appCode;
            paramDict["timestamp"] = Convert.ToInt64(ts.TotalMilliseconds).ToString();

            string token = GetToken(paramDict, path);
            paramDict["token"] = token;
        }

        /// <summary>
        /// 获取md5字符串
        /// </summary>
        /// <param name="str">待处理的字符串</param>
        /// <returns></returns>
        private static string GetMd5String(string str)
        {
            MD5CryptoServiceProvider crypto = new MD5CryptoServiceProvider();
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            byte[] signBytes = crypto.ComputeHash(bytes);
            string result = BitConverter.ToString(signBytes);
            return result.Replace("-", "").ToLower();
        }

        /// <summary>
        /// 获取sha1字符串
        /// </summary>
        /// <param name="str">待处理的字符串</param>
        /// <returns></returns>
        private static string GetSha1String(string str)
        {
            SHA1CryptoServiceProvider crypto = new SHA1CryptoServiceProvider();
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            byte[] signBytes = crypto.ComputeHash(bytes);
            string result = BitConverter.ToString(signBytes);
            return result.Replace("-", "").ToLower();
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="paramDict">参数字典</param>
        /// <param name="path">请求路径</param>
        /// <returns></returns>
        private static string GetToken(Dictionary<string, string> paramDict, string path)
        {
            string secret = appSecret;
            StringBuilder builder = new StringBuilder();
            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(paramDict);
            list.Sort((s1, s2) => String.Compare(s1.Key, s2.Key, StringComparison.Ordinal));
            foreach (KeyValuePair<string, string> item in list)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                }
            }

            builder.Append(path);
            Console.WriteLine("buf:" + builder.ToString());

            string md5 = GetMd5String(builder.ToString());
            Console.WriteLine("md5:" + md5);
            string waitSign = md5 + secret;
            string sign = GetSha1String(waitSign);
            Console.WriteLine("sign:" + sign);
            return sign;
        }
    }
}